import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *Description:
 *Version:1.0.0
 *@author shihb
 *@date 2020/5/23 17:40
 */
public class ThreadLockDemo {

  public static void main(String[] args) {
    SellTickets2 st = new SellTickets2();
    new Thread(()->{
      for(int i = 0; i < 30; i++) {
        st.sell();
      }
    },"a").start();
    new Thread(()->{
      for(int i = 0; i < 30; i++) {
        st.sell();
      }
    },"b").start();
    new Thread(()->{
      for(int i = 0; i < 30; i++) {
        st.sell();
      }
    },"c").start();

  }
}
class SellTickets{
  private int num=30;
  public synchronized void  sell(){
    if (num > 0) {
      System.out.println("正在卖"+(num--)+"张票还剩"+num);
    }
  }
}
class SellTickets2{
  private int num=30;
  Lock lock = new ReentrantLock();
  public  void  sell(){

    lock.lock();
    try {
      if (num > 0) {
        System.out.println(Thread.currentThread().getName()+"正在卖"+(num--)+"张票还剩"+num);
      }
    }catch (Exception e){
      e.printStackTrace();
    }finally {
      lock.unlock();
    }

  }
}
